package org.ruanjj.atoi;

public class Solution {
    public int myAtoi(String s){
        s = s.trim();
        if(s.length() == 0){
            return 0;
        }
        int res = 0;
        int beginIndex = 0;

        int symbol = 1;
        if(s.charAt(beginIndex) == '-'){
            symbol = -1;
            beginIndex++;
        }else if(s.charAt(beginIndex) == '+'){
            beginIndex++;
        }
        //[−231,  231 − 1]  ——> [-2147483648, 2147683647]
        for(int i = beginIndex; i < s.length(); i++){
            if(Character.isDigit(s.charAt(i))){
                if(res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10 && s.charAt(i)-'0' > 7)){
                    if(symbol == -1){
                        return Integer.MIN_VALUE;
                    }else{
                        return Integer.MAX_VALUE;
                    }
                }
                res = (s.charAt(i)-'0') + res * 10;
            }else{
                break;
            }
        }

        return symbol * res;
    }
}
